package com.yuexunit.mobilenurse.module.DocAdvice.presenter.impl;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.Dispensing_List_New;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Dispensing_New;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_OrderDetail;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_OrderExec;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Orderlist;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXDocAdviceBean;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXExecuteOrder;
import com.yuexunit.mobilenurse.module.DocAdvice.model.IDispensingModel;
import com.yuexunit.mobilenurse.module.DocAdvice.presenter.IDispensingPresenter;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.view.IDispensingView;
import com.yuexunit.mobilenurse.module.PatientDetail.model.impl.PatientDetailModel;
import com.yuexunit.mobilenurse.util.ProUtil;
import com.yuexunit.mobilenurse.util.RxUtils;

import org.json.JSONObject;
import org.kymjs.kjframe.ui.ViewInject;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by work-jx on 2016/2/3.
 */
public class DispensingPresenter implements IDispensingPresenter{
    //记录Log
    private final Logger log = ProUtil.getLogger(PatientDetailModel.class);
    private IDispensingModel model;
    private IDispensingView view;
    private CompositeSubscription compositeSubscription = new CompositeSubscription();
    ArrayList<DocAdvice_Dispensing_New> docAdvice_dispensing_news = new ArrayList<DocAdvice_Dispensing_New>();

    public DispensingPresenter(IDispensingView view,IDispensingModel model)
    {
        this.view = view;
        this.model = model;
    }


    @Override
    public void showDispensingList(String visitno) {
        compositeSubscription.add(
                model.getDispensingListData(visitno)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("jx",e+"");
                                ViewInject.toast("发药暂无数据");
                                view.showDispensingList(docAdvice_dispensing_news);
                            }

                            @Override
                            public void onNext(String result) {
                                YXDocAdviceBean Total = JSON.parseObject(result, YXDocAdviceBean.class);
                                YXDocAdviceBean DocAdviceData = Total.getBody();
                                Log.v("jx", DocAdviceData.getHead().getRet_code());
                                if ("0".equals(DocAdviceData.getHead().getRet_code())) {

                                    List<DocAdvice_Orderlist> docadvice_orderlist;
                                    List<DocAdvice_OrderDetail> docadvice_orderdetail;
                                    List<DocAdvice_OrderExec> docAdvice_orderexec;

                                    String orderlist = DocAdviceData.getResponse().getOrderlist();
                                    String orderlist_first = orderlist.substring(0, 1);
                                    if (!orderlist_first.equals("[")) {
                                        orderlist = "[" + orderlist + "]";
                                        docadvice_orderlist = JSON.parseArray(orderlist, DocAdvice_Orderlist.class);
                                    } else {
                                        docadvice_orderlist = JSON.parseArray(orderlist, DocAdvice_Orderlist.class);
                                    }

                                    String orderdetail = DocAdviceData.getResponse().getOrderdetail();
                                    String orderdetail_first = orderdetail.substring(0, 1);
                                    if (!orderdetail_first.equals("[")) {
                                        orderdetail = "[" + orderdetail + "]";
                                        docadvice_orderdetail = JSON.parseArray(orderdetail, DocAdvice_OrderDetail.class);
                                    } else {
                                        docadvice_orderdetail = JSON.parseArray(orderdetail, DocAdvice_OrderDetail.class);
                                    }

                                    String orderexec = DocAdviceData.getResponse().getOrderexec();
                                    if (!("null".equals(orderexec))) {
                                        String orderexec_first = orderexec.substring(0, 1);
                                        if (!orderexec_first.equals("[")) {
                                            orderexec = "[" + orderexec + "]";
                                            docAdvice_orderexec = JSON.parseArray(orderexec, DocAdvice_OrderExec.class);
                                        } else {
                                            docAdvice_orderexec = JSON.parseArray(orderexec, DocAdvice_OrderExec.class);
                                        }
                                    } else {
                                        docAdvice_orderexec = null;
                                    }

                                    for(int i = 0 ;i<docadvice_orderdetail.size();i++)
                                    {
                                        if(docadvice_orderdetail.get(i).getMedbarcode()!=null) {
                                            boolean iscontain = false;
                                           for(int j = 0 ; j< docAdvice_dispensing_news.size();j++)
                                           {
                                               if(docadvice_orderdetail.get(i).getMedbarcode().equals(docAdvice_dispensing_news.get(j).getBarcode()))
                                               {
                                                   iscontain = true;

                                                   Dispensing_List_New dispensing_list_new = new Dispensing_List_New();
                                                   dispensing_list_new.setMedname(docadvice_orderdetail.get(i).getMedname());
                                                   dispensing_list_new.setNum(docadvice_orderdetail.get(i).getNum());
                                                   dispensing_list_new.setDosage(docadvice_orderdetail.get(i).getDosage()+"");
                                                   dispensing_list_new.setDoseusnit(docadvice_orderdetail.get(i).getDoseusnit());

                                                   for(int z = 0 ;z<docadvice_orderlist.size();z++)
                                                   {
                                                       if(docadvice_orderdetail.get(i).getOrdergroupno() == docadvice_orderlist.get(z).getOrdergroupno())
                                                       {
                                                           dispensing_list_new.setExecfreq(docadvice_orderlist.get(z).getExecfreq());
                                                           dispensing_list_new.setExecway(docadvice_orderlist.get(z).getExecway());
                                                       }
                                                   }

                                                   for (int k = 0 ;k <docAdvice_orderexec.size();k++)
                                                   {
                                                       if(docadvice_orderdetail.get(i).getOrdergroupno() == docAdvice_orderexec.get(k).getOrdergroupno()
                                                               &&docadvice_orderdetail.get(i).getMedbarcode().equals(docAdvice_orderexec.get(k).getBarcode()))
                                                       {
                                                           dispensing_list_new.setExecdate(docAdvice_orderexec.get(k).getExecdate());
                                                           dispensing_list_new.setExectime(docAdvice_orderexec.get(k).getExectime());
                                                           dispensing_list_new.setExecempid(docAdvice_orderexec.get(k).getExecempid()+"");
                                                       }
                                                   }

                                                   docAdvice_dispensing_news.get(j).getDispensing_list_news().add(dispensing_list_new);
                                               }
                                           }

                                            if(!iscontain)
                                            {
                                                DocAdvice_Dispensing_New docAdvice_dispensing_new = new DocAdvice_Dispensing_New();
                                                docAdvice_dispensing_new.setBarcode(docadvice_orderdetail.get(i).getMedbarcode());

                                                Dispensing_List_New dispensing_list_new = new Dispensing_List_New();
                                                dispensing_list_new.setMedname(docadvice_orderdetail.get(i).getMedname());
                                                dispensing_list_new.setNum(docadvice_orderdetail.get(i).getNum());
                                                dispensing_list_new.setDosage(docadvice_orderdetail.get(i).getDosage()+"");
                                                dispensing_list_new.setDoseusnit(docadvice_orderdetail.get(i).getDoseusnit());

                                                for(int z = 0 ;z<docadvice_orderlist.size();z++)
                                                {
                                                    if(docadvice_orderdetail.get(i).getOrdergroupno() == docadvice_orderlist.get(z).getOrdergroupno())
                                                    {
                                                        dispensing_list_new.setExecfreq(docadvice_orderlist.get(z).getExecfreq());
                                                        dispensing_list_new.setExecway(docadvice_orderlist.get(z).getExecway());
                                                    }
                                                }

                                                for (int k = 0 ;k <docAdvice_orderexec.size();k++)
                                                {
                                                    if(docadvice_orderdetail.get(i).getOrdergroupno() == docAdvice_orderexec.get(k).getOrdergroupno()
                                                       &&docadvice_orderdetail.get(i).getMedbarcode().equals(docAdvice_orderexec.get(k).getBarcode()))
                                                    {
                                                        dispensing_list_new.setExecdate(docAdvice_orderexec.get(k).getExecdate());
                                                        dispensing_list_new.setExectime(docAdvice_orderexec.get(k).getExectime());
                                                        dispensing_list_new.setExecempid(docAdvice_orderexec.get(k).getExecempid()+"");
                                                    }
                                                }
                                                Log.e("jx", "dispensing_list_new info");
                                                if(docAdvice_dispensing_new.getDispensing_list_news() == null)
                                                {
                                                    ArrayList<Dispensing_List_New>  dispensing_list_news = new ArrayList<Dispensing_List_New>();
                                                    dispensing_list_news.add(dispensing_list_new);
                                                    docAdvice_dispensing_new.setDispensing_list_news(dispensing_list_news);
                                                }

                                                docAdvice_dispensing_news.add(docAdvice_dispensing_new);
                                            }
                                        }
                                    }

                                    for (int i = 0 ;i<docAdvice_dispensing_news.size();i++)
                                    {
                                        if(docAdvice_dispensing_news.get(i).getDispensing_list_news().get(0).getExectime() == null)
                                        {
                                            docAdvice_dispensing_news.get(i).setStatus("等待发药");
                                            docAdvice_dispensing_news.get(i).setCount("0/1");
                                        }
                                        else {
                                            docAdvice_dispensing_news.get(i).setStatus("已发药");
                                            docAdvice_dispensing_news.get(i).setCount("1/1");
                                        }
                                    }


                                    if(docAdvice_dispensing_news.size() == 0)
                                    {
                                        ViewInject.toast("发药暂无数据");
                                    }
                                }
                                view.showDispensingList(docAdvice_dispensing_news);
                            }
                        }));
    }


    @Override
    public void Execorder(final boolean source,String visitno, String barcode, String nurseid) {
        compositeSubscription.add(
                model.ExecOrder(visitno, barcode, nurseid)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<String>() {

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                if(source) {
                                    view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.NETERROR);
                                }else{
                                    view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.NETERROR);
                                }
                            }

                            @Override
                            public void onNext(String result) {
                                JSONObject all, body;
                                String reponse = null;
                                try {
                                    all = new JSONObject(result.toString());
                                    body = all.getJSONObject("body");
                                    reponse = body.getString("response");
                                } catch (Exception e) {
                                    log.error("Exception:"+e);
                                    if(source) {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.NETERROR);
                                    }
                                    else {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.NETERROR);
                                    }
                                }

                                if(!("null".equals(reponse))) {
                                    YXExecuteOrder Total = JSON.parseObject((String) result.toString(), YXExecuteOrder.class);
                                    YXExecuteOrder executeOrderData = Total.getBody();

                                    if (source) {
                                        if ("0".equals(executeOrderData.getHead().getRet_code())) {
                                            view.execDialog(AppConfig.EXEC_DIALOG_PASS_EXTERNAL,"");
                                        } else {
                                            view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.MISMATCH);
                                        }
                                    } else {
                                        if ("0".equals(executeOrderData.getHead().getRet_code())) {
                                            view.getExecData(executeOrderData);
                                           view.execDialog(AppConfig.EXEC_DIALOG_PASS_INNER,"");
                                        } else {
                                            view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.MISMATCH);
                                        }
                                    }
                                }
                                else {
                                    if(source) {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.UNSUCESS);
                                    }
                                    else {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.UNSUCESS);
                                    }
                                }
                            }
                        })
        );
    }

    public CompositeSubscription getCompositeSubscription() {
        return RxUtils.getNewCompositeSubIfUnsubscribed(compositeSubscription);
    }

    public void UnSubObservers() {
        if (compositeSubscription != null && !compositeSubscription.isUnsubscribed()) {
            compositeSubscription.unsubscribe();
        }

    }
}
